package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// MiniRechargePackageController 处理小程序充值套餐相关请求
type MiniRechargePackageController struct {
	web.Controller
}

// List 获取充值套餐列表
func (c *MiniRechargePackageController) List() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
			"data":    err,
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	packageType, err := c.GetInt8("type", 1) // 默认获取全国通用套餐
	if err != nil || (packageType != 1 && packageType != 2) {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "套餐类型无效",
		}
		c.ServeJSON()
		return
	}

	// 获取门店ID（仅在类型为2时使用）
	storeId, _ := c.GetInt64("store_id", 0)
	if packageType == 2 && storeId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店ID无效",
		}
		c.ServeJSON()
		return
	}

	// 获取充值套餐列表
	packages, err := models.GetRechargePackagesByType(packageType, storeId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值套餐失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取充值套餐成功",
		"data": map[string]interface{}{
			"list": packages,
		},
	}
	c.ServeJSON()
}

// Get 获取充值套餐详情
func (c *MiniRechargePackageController) Get() {
	// 获取当前会员信息
	member, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || member == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	id, err := c.GetInt64("id", 0)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "套餐ID无效",
		}
		c.ServeJSON()
		return
	}

	// 获取充值套餐详情
	pkg, err := models.GetRechargePackageById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取充值套餐详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 检查套餐状态
	if pkg.Status != 1 || pkg.IsDeleted == 1 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "充值套餐不可用",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取充值套餐详情成功",
		"data":    pkg,
	}
	c.ServeJSON()
}
